/*
 * @Author: your name
 * @Date: 2021-04-17 08:46:32
 * @LastEditTime: 2021-04-17 20:45:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \xmall_vue\src\router\index.js
 */
import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import routes from './routes'

const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace

VueRouter.prototype.replace = function(location,onResolved,onRejected){
  if(onResolved === undefined && onRejected === undefined){
    originReplace.call(this,location).catch(()=>{})
  }else{
    return originReplace.call(this,location,onResolved,onRejected)
  }
}

VueRouter.prototype.push = function(location,onResolved,onRejected){
  if(onResolved === undefined && onRejected === undefined){
    originPush.call(this,location).catch(()=>{})
  }else{
    return originPush.call(this,location,onResolved,onRejected)
  }
}
const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    return {
      x: 0,
      y: 0
    }
  }
})
router.beforeEach(async (to, from, next) => {
  let token = store.state.userInfo.token
  let userInfo = store.state.userInfo.userInfo
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (userInfo.name) {
        next()
      } else {
        try {
          await store.dispatch('getUserInfo')
          next()
        } catch (error) {
          //如果没有获取到用户信息,说明token过期,需清空token,并重新登录获取token
          await store.dispatch('resetToken')
          next('/login')
        }
      }
    }
  } else {
    let targetPath = to.path
    if( targetPath.startsWith('/pay') || targetPath.startsWith('/paysuccess') || targetPath.startsWith('/payload') || targetPath.startsWith('/payinfo') || targetPath.startsWith('/shopCart')){
      next(`/login?redirect=` + targetPath)
    }else{
      next()
    }
  }
})
export default router